<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男" name="sex">男</option>
        <option value="女" name="sex">女</option>
      </select>
    </div>
    <div>
      <button @click="toggle">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(obj, index) in arr" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ obj.uname }}</td>
          <td>{{ obj.age }}</td>
          <td>{{ obj.sex }}</td>
          <td>
            <button @click="delFn(index)">删除</button>
            <button @click="change(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      arr: [
        { uname: "Tom", age: 18, sex: "男" },
        { uname: "Jone", age: 20, sex: "女" },
      ],
      uname: "",
      age: "",
      sex: "男",
      currentIndex: -1,
    };
  },
  methods: {
    // 根据索引删除对应数据
    delFn(index) {
      this.arr.splice(index, 1);
    },
    // 根据索引将对应的数据内容重新填入输入框 同时将currentIndex赋值为当前的索引
    change(index) {
      this.uname = this.arr[index].uname;
      this.age = this.arr[index].age;
      this.sex = this.arr[index].sex;
      this.currentIndex = index;
    },
    // 添加或修改
    toggle() {
      console.log(this.currentIndex);
      // 根据当前的currentIndex值判断修改或添加
      // 用三元表达式判断 currentIndex为-1说明没有要进行修改的数据 不为-1则进行修改操作
      this.currentIndex === -1
        ? this.arr.push({ uname: this.uname, age: this.age, sex: this.sex })
        : // 修改 把当前索引指向的数据删除，并在该位置重新插入数据
          this.arr.splice(this.currentIndex, 1, {
            uname: this.uname,
            age: this.age,
            sex: this.sex,
          });
    },
  },
};
</script>